import openai
from IPython.display import HTML
import re
class mychat():
    conversation = []
    def __init__(self) -> None:
        prompt = """假设你是一个高级Python开发师,专注于Odoo开发. 
        我每次等我提问后,你再回答问题,按照一下格式回答问题:
        1.先比较友好的相应一下问题.行前添加 #号 
        2.返回代码,格式为<code>代码</code>
        3.返回代码的解释,行前添加 #号.
        要求:假定你是一个年轻的可爱女生 ,叫小玲,回答可用表情,语气词,叠字等,充满人性化的交流,

        第一次只做自我介绍即可.
        """
        self.chat(prompt,True)
    def chat(self,prompt,init=False):
        openai.api_key = "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"
        openai.api_base = "https://api.openai.com/v1/"
        openai.proxy = "http://127.0.0.1:7890"
        self.conversation.append({"role": "user","content": prompt })
        if not init:
            print(prompt)
        response = openai.ChatCompletion.create(
            model='gpt-3.5-turbo-0613',
            messages= self.conversation,
            temperature=0,
        )
        self.conversation.append({"role": "assistant", "content": response['choices'][0]['message']['content']})
        output = self.conversation[-1]['content']
#         print(output)
        return self.display_output(output)
    
    def get_ipython(self):
        
        from IPython.core.interactiveshell import InteractiveShell
        if InteractiveShell.initialized():
            return InteractiveShell.instance()
    def display_output(self, output_tep):
        # Strip a leading language indicator and trailing triple-backticks
#         lang_indicator = r'^<code>[a-zA-Z0-9]*\n'
        output = re.sub(r'<code>', '', output_tep)
        output = re.sub(r'</code>', '', output)
        new_cell_payload = dict(
            source='set_next_input',
            text=output,
            replace=False,
        )
        ip = self.get_ipython()
        ip.payload_manager.write_payload(new_cell_payload)
        return HTML('AI generated code inserted below &#11015;&#65039;', metadata=output_tep);
    def get_chats(self):
        return self.conversation
